package com.example.javaproject.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javaproject.common.R;
import com.example.javaproject.dto.TeacherStatsDTO;
import com.example.javaproject.entity.Position;
import com.example.javaproject.service.PositionService;
import com.example.javaproject.service.TeacherService;
import com.example.javaproject.entity.Teacher;
import com.example.javaproject.util.JwtUtil;
import io.jsonwebtoken.Claims;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/position")
public class PositionController {
    @Autowired
    private PositionService positionService;
    @Autowired
    private TeacherService teacherService;

    @GetMapping("/list")
    public R list(
        @RequestParam(defaultValue = "1") Integer page,
        @RequestParam(defaultValue = "10") Integer size,
        @RequestParam(required = false) String name,
        @RequestParam(required = false) String location,
        @RequestParam(required = false) Integer status
    ) {
        try {
            List<Map<String, Object>> positions = positionService.getAllPositionsWithTeacher();

            // 手动实现分页和筛选
            List<Map<String, Object>> filteredList = positions.stream()
                .filter(pos -> {
                    boolean nameMatch = name == null || name.isEmpty() ||
                        (pos.get("name") != null && String.valueOf(pos.get("name")).contains(name));
                    boolean locationMatch = location == null || location.isEmpty() ||
                        (pos.get("location") != null && String.valueOf(pos.get("location")).contains(location));
                    boolean statusMatch = status == null ||
                        (pos.get("status") != null && Integer.valueOf(String.valueOf(pos.get("status"))).equals(status));
                    return nameMatch && locationMatch && statusMatch;
                })
                .sorted((a, b) -> {
                    if (status == null && a != null && b != null && a.get("status") != null && b.get("status") != null) {
            // status为null时，先按status=0再status=1排序
                        return Integer.valueOf(String.valueOf(a.get("status")))
                            .compareTo(Integer.valueOf(String.valueOf(b.get("status"))));
                    }
                    return 0;
                })
                .skip((page - 1) * size)
                .limit(size)
                .toList();

            // 构建分页对象
            Page<Map<String, Object>> pageObj = new Page<>(page, size);
            pageObj.setRecords(filteredList);
            pageObj.setTotal(positions.size());

            return R.ok(pageObj);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取岗位列表失败：" + e.getMessage());
        }
    }

    @PostMapping("/add")
    public R add(@RequestBody Position position, HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未提供授权");
        }
        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer role = claims.get("role", Integer.class);

        if (role == 2) { // 角色为教师
            Integer userId = claims.get("userId", Integer.class);
            Teacher teacher = teacherService.getByUserId(userId);
            if (teacher == null) {
                return R.error("无法找到当前登录用户的教师信息");
            }
            position.setTeacherId(teacher.getId());
        } else if (role == 0) { // 角色为管理员
            if (position.getTeacherId() == null) {
                return R.error("管理员新增岗位时必须指定教师");
            }
            // (可选) 校验 teacherId 是否真实存在
            if (teacherService.getById(position.getTeacherId()) == null) {
                return R.error("指定的教师不存在");
            }
        } else {
            return R.error("无权进行此操作");
        }

        position.setIsDeleted(0);
        position.setCreateTime(new java.util.Date());
        position.setUpdateTime(new java.util.Date());

        boolean success = positionService.save(position);
        return success ? R.ok(null) : R.error("岗位发布失败");
    }

    @PutMapping("/update")
    public R update(@RequestBody Position position, @RequestHeader("Authorization") String token) {
        // 解析token
        String realToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        Claims claims = com.example.javaproject.util.JwtUtil.parseToken(realToken);
        Integer role = claims.get("role", Integer.class);
        Integer userId = claims.get("userId", Integer.class);
        if (role == null || userId == null) {
            return R.error("未登录或token无效");
        }
        if (role == 2) { // 教师
            Teacher teacher = teacherService.getByUserId(userId);
            if (teacher == null) {
                return R.error("教师信息不存在");
            }
            // 查询岗位
            Position dbPosition = positionService.getById(position.getId());
            if (dbPosition == null || dbPosition.getIsDeleted() != 0) {
                return R.error("岗位不存在");
            }
            if (!dbPosition.getTeacherId().equals(teacher.getId())) {
                return R.error("无权操作他人岗位");
            }
        }
        // 管理员可操作所有岗位
        boolean success = positionService.updatePosition(position);
        return success ? R.ok(null) : R.error("修改失败");
    }

    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Integer id, @RequestHeader("Authorization") String token) {
        // 解析token
        String realToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        Claims claims = com.example.javaproject.util.JwtUtil.parseToken(realToken);
        Integer role = claims.get("role", Integer.class);
        Integer userId = claims.get("userId", Integer.class);
        if (role == null || userId == null) {
            return R.error("未登录或token无效");
        }
        if (role == 2) { // 教师
            Teacher teacher = teacherService.getByUserId(userId);
            if (teacher == null) {
                return R.error("教师信息不存在");
            }
            // 查询岗位
            Position dbPosition = positionService.getById(id);
            if (dbPosition == null || dbPosition.getIsDeleted() != 0) {
                return R.error("岗位不存在");
            }
            if (!dbPosition.getTeacherId().equals(teacher.getId())) {
                return R.error("无权操作他人岗位");
            }
        }
        // 管理员可操作所有岗位
        boolean success = positionService.deleteById(id);
        return success ? R.ok(null) : R.error("删除失败");
    }

    @GetMapping("/stats")
    public R getStats() {
        try {
            List<Map<String, Object>> stats = positionService.getPositionStats();
            return R.ok(stats);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @GetMapping("/teacher-stats")
    public R getTeacherStats(HttpServletRequest request) {
        try {
            // 从JWT token中获取userId
            String authHeader = request.getHeader("Authorization");
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return R.error("未提供认证token");
            }
            String token = authHeader.substring(7);
            Claims claims = JwtUtil.parseToken(token);
            Integer userId = claims.get("userId", Integer.class);
            Integer role = claims.get("role", Integer.class);
            // 验证是否为教师角色
            if (role == null || role != 2) { // 假设2是教师角色
                return R.error("权限不足，仅教师可查看此统计");
            }
            // 查找teacherId
            Teacher teacher = teacherService.getByUserId(userId);
            if (teacher == null) {
                return R.error("教师信息不存在");
            }
            Integer teacherId = teacher.getId();
            TeacherStatsDTO stats = positionService.getTeacherStats(teacherId);
            return R.ok(stats);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取教师统计数据失败: " + e.getMessage());
        }
    }

    @GetMapping("/application-stats")
    public R getApplicationStats() {
        try {
            List<Map<String, Object>> stats = positionService.getApplicationStats();
            return R.ok(stats);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取岗位申请统计失败: " + e.getMessage());
        }
    }

    @GetMapping("/teacher-list")
    public R teacherList(
        @RequestHeader("Authorization") String token,
        @RequestParam(defaultValue = "1") Integer page,
        @RequestParam(defaultValue = "8") Integer size,
        @RequestParam(required = false) String name,
        @RequestParam(required = false) String location,
        @RequestParam(required = false) Integer status
    ) {
        // 解析token获取userId
        String realToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        Integer userId = null;
        try {
            io.jsonwebtoken.Claims claims = com.example.javaproject.util.JwtUtil.parseToken(realToken);
            Object idObj = claims.get("userId");
            if (idObj instanceof Integer) {
                userId = (Integer) idObj;
            } else if (idObj instanceof Number) {
                userId = ((Number) idObj).intValue();
            } else if (idObj != null) {
                userId = Integer.parseInt(idObj.toString());
            }
        } catch (Exception e) {
            return R.error("token无效或已过期");
        }
        if (userId == null) {
            return R.error("未登录或token无效");
        }
        // 通过 userId 查 teacherId
        com.example.javaproject.entity.Teacher teacher = teacherService.getByUserId(userId);
        if (teacher == null) {
            return R.error("未找到对应教师信息");
        }
        // 查询
        java.util.Map<String, Object> params = new java.util.HashMap<>();
        params.put("teacherId", teacher.getId());
        params.put("page", page);
        params.put("size", size);
        params.put("name", name);
        params.put("location", location);
        params.put("status", status);
        java.util.Map<String, Object> result = positionService.getTeacherPositions(params);
        return R.ok(result);
    }
}
